package com.hjt.gulimall.cart.interceptor;

import com.hjt.common.constant.AuthConstant;
import com.hjt.common.constant.CartConstant;
import com.hjt.common.to.member.UserLoginTo;
import com.hjt.gulimall.cart.vo.UserLoginVo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 拦截器
 *  登录：session有信息
 *  没登陆：按照cookie中的用户标识临时标识一个用户
 *  cookie中没有：给用户一个标识
 *
 * @author:97007
 * @date:2021/10/1 9:58
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserLoginVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
        * 登录：session有信息
        * 没登陆：按照cookie中的用户标识临时标识一个用户
        * cookie中没有：给用户一个标识
        */
        UserLoginTo loginUser = (UserLoginTo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
        UserLoginVo userLoginVo = new UserLoginVo();
        if (loginUser != null) {
            // 登录了设置userId
            userLoginVo.setUserId(loginUser.getId());
        }
        // 没登陆,在cookie中找userKey
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstant.TEMP_USER_KEY_COOKIE_NAME)) {
                    userLoginVo.setUserKey(cookie.getValue());
                    userLoginVo.setTempUser(true); // 设置为临时用户
                    break;
                }
            }
        }
        // 没有临时用户标识，生成一个
        if (!StringUtils.hasLength(userLoginVo.getUserKey())) {
            String userKey = UUID.randomUUID().toString();
            userLoginVo.setUserKey(userKey);
        }
        threadLocal.set(userLoginVo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        // 如果有user-key，放到cookie中
        UserLoginVo userLoginVo = threadLocal.get();
        // 不是临时用户，首次生成user-key，放入到cookie中
        if (!userLoginVo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_KEY_COOKIE_NAME, userLoginVo.getUserKey());
            cookie.setMaxAge(CartConstant.TEMP_USER_KEY_COOKIE_MAX_AGE);
            cookie.setDomain("gulimall.com");
            response.addCookie(cookie);
        }
    }
}
